package com.resou.reader.discovery.bookdetail;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.resou.reader.R;
import com.resou.reader.activity.freebook.FreeBookActivity;
import com.resou.reader.activity.friendboost.FriendBoostActivity;
import com.resou.reader.api.entry.BookListBean;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookdetail.BookDetailActivity;
import com.resou.reader.discovery.comment.CommentActivity;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.reader.utils.BitmapUtils;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.UserUtil;
import com.resou.reader.utils.ViewHelper;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.FlowLayout;
import com.resou.reader.view.Loading;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 书单详情页面
 */
public class BookListActivity extends ResouBaseActivity<BookListPresenter> implements IBookListContract.IBookListView, OnRefreshLoadMoreListener {
    private static final String TAG = "BookListPresenter";
    @BindView(R.id.tvCommentNum)
    TextView tvCommentNum;
    @BindView(R.id.tvCollectionNum)
    TextView tvCollectionNum;

    /**
     * 启动书单详情页面
     *
     * @param context
     * @param bookListId 书id
     */
    public static void start(Context context, String bookListId, String url) {
        Intent starter = new Intent(context, BookListActivity.class);
        starter.putExtra("bookListId", bookListId);
        starter.putExtra("url", url);
        context.startActivity(starter);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.anim_detail_enter, R.anim.anim_no);
        }
    }


    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mSmartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.llComment)
    LinearLayout llComment;
    @BindView(R.id.llCollection)
    LinearLayout llCollection;
    @BindView(R.id.llShare)
    LinearLayout llShare;
    @BindView(R.id.ll_bottomMenu)
    LinearLayout llBottomMenu;
    @BindView(R.id.ivCollection)
    ImageView ivCollection;
    /**
     * 头部信息
     */
    TextView tvBookName; //书名
    TextView tvPageView;//浏览量
    TextView tvLabel;//标签
    FlowLayout llLabelContent;
    TextView tvDes;//书描述
    TextView tvNumAndCollection;//书描述
    TextView tvTime;//时间

    BookListAdapter bookListAdapter;
    List<BookListBean.ListBookBean.BooksBean> data;
    AlertDialog.Builder builder = null;
    AlertDialog dialog = null;
    String bookListId = "";
    int page = 0;

    boolean isCollection = false;
    int collectionNum = 0;
    String title = "";
    String description = "";
    int pos = 0;
    ShareAction shareAction;

    @Override
    protected void initStatusBar() {

    }

    @Override
    protected void initPresenter() {
        mPresenter = new BookListPresenter(this);
    }

    @Override
    protected void initView() {

        PushAgent.getInstance(this).onAppStart();
        tvTitle.setText("书单详情");
        initDialog();
        bookListAdapter = new BookListAdapter(R.layout.adapter_booklist, data);
        bookListAdapter.addHeaderView(getHeaderView());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mSmartRefreshLayout.setOnRefreshLoadMoreListener(this);
        ClassicsFooter.REFRESH_FOOTER_NOTHING = "已经全部加载完毕";
        mSmartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
//        bookListAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        mRecyclerView.setAdapter(bookListAdapter);
        bookListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BookListBean.ListBookBean.BooksBean booksBean = (BookListBean.ListBookBean.BooksBean) adapter.getData().get(position);
                switch (view.getId()) {
                    /**
                     *详情
                     */
                    case R.id.llBookContentOnclick:
                        BookDetailActivity.startDetailActivity(getApplication(), booksBean.getNovelId());
                        break;
                    /**
                     * 加入到书架
                     */
                    case R.id.tvAddBookList:
                        if (NetworkUtils.isNetworkConnected(BookListActivity.this)) {
                            pos = position;
                            mPresenter.addBookListLogined(booksBean.getNovelId());
                        } else {
                            ToastUtil.makeShortToast("网络异常");
                        }

                        break;
                    /**
                     * 点赞
                     */
                    case R.id.llPraise:
                        if (NetworkUtils.isNetworkConnected(BookListActivity.this)) {
                            pos = position;
                            if (booksBean.getUserLike() == 1) {
                                mPresenter.cancellBookLike(booksBean.getNovelId());
                            } else {
                                mPresenter.bookLike(booksBean.getNovelId());
                            }
                        } else {
                            ToastUtil.makeShortToast("网络异常");
                        }

                        break;
                }
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_book_list;
    }

    @Override
    public void retryRefreshData() {
        page = 0;
        mPresenter.quearBookListDetail(bookListId, page);
    }

    @OnClick({R.id.ivBack, R.id.llComment, R.id.llCollection, R.id.llShare})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            /**
             * 评论
             */
            case R.id.llComment:
                CommentActivity.start(BookListActivity.this, bookListId);
                break;
            /**
             * 收藏
             */
            case R.id.llCollection:
                if (NetworkUtils.isNetworkConnected(this)) {
                    if (isCollection) {
                        mPresenter.cancellCollection(bookListId);
                    } else {
                        mPresenter.collectionBookList(bookListId);
                    }
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }

                break;
            /**
             * 分享
             */
            case R.id.llShare:
                if (isNetwork()) {
                    String url = getIntent().getStringExtra("url");
                    UMWeb web = new UMWeb("https://testpc.resouxs.com/bookList/" + bookListId);
                    web.setTitle("平台补贴，海量正版书籍免费看！");
                    if (TextUtils.isEmpty(url)) {
                        web.setThumb(new UMImage(this, R.mipmap.logo));
                    } else {
                        web.setThumb(new UMImage(this, url));
                    }
                    web.setDescription("我正在看《" + title + "》" + description);
                    shareAction = new ShareAction(this)
                            .withMedia(web)
                            .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE)
                            .setCallback(umShareListener);
                    shareAction.open();
                }
                break;
        }
    }

    @Override
    public void initData() {
        bookListId = getIntent().getStringExtra("bookListId");
//        page = 0;
//        mPresenter.quearBookListDetail(bookListId, page);
    }

    @Override
    public void showContent() {
        dissLoading();
    }

    @Override
    public void showProgress() {
        showLoading();
    }

    @Override
    public void showError(Throwable throwable) {
        dissLoading();
        Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
        if (page == 0) {
            showNetErrorView(R.id.rlContent);
        }
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        mPresenter.quearBookListDetail(bookListId, page);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 0;
        mPresenter.quearBookListDetail(bookListId, page);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        page = 0;
        mPresenter.quearBookListDetail(bookListId, page);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (llLabelContent != null) {
            llLabelContent.removeAllViews();
        }
        if (null != dialog) {
            dialog.dismiss();
        }
        EventBus.getDefault().unregister(this);
        dissLoading();
    }

    @Override
    public void showDetail(BookListBean listBeans) {
        tvBookName.setText(listBeans.getBookListName() + "");
        tvPageView.setText("浏览量：" + listBeans.getViewCount() + "");
//        tvLabel.setText(listBeans.getBookListLabel() + "");
        if (llLabelContent != null) {
            llLabelContent.removeAllViews();
        }
        ViewHelper.setLabelView(this, llLabelContent, listBeans.getBookListLabel());
        tvDes.setText(listBeans.getBookListRecommend() + "");
        tvNumAndCollection.setText(listBeans.getBookCount() + "本  |  " + listBeans.getCollectionCount() + "收藏");
        tvTime.setText(DateUtils.transferLongToDate("yyyy-MM-dd", listBeans.getUploadDate()) + "");
        tvCommentNum.setText("评论（" + listBeans.getCommentCount() + "）");
        tvCollectionNum.setText("收藏（" + listBeans.getCollectionCount() + "）");
        description = listBeans.getBookListRecommend();
        title = listBeans.getBookListName();
        collectionNum = listBeans.getCollectionCount();
        if (1 == listBeans.getUserCollection()) {
            isCollection = true;
            ivCollection.setImageResource(R.mipmap.ic_booklist_collectioned);
        } else {
            isCollection = false;
            ivCollection.setImageResource(R.mipmap.ic_booklist_collection);
        }
        //判断是否登录 已登录时 直接 用接口数据 ，否则 需要同步本地的书架 来同步是否加入书架
        if (UserInstance.isLogin()) {
            Log.i(TAG, "showDetail: 已登录");
            showAuthor(listBeans.getListBook().getBooks());
        } else {
            Log.i(TAG, "showDetail: 未登录");
            mPresenter.requestlocalSysRemoteBookList(listBeans.getListBook().getBooks());
        }
    }

    @Override
    public void showAuthor(List<BookListBean.ListBookBean.BooksBean> listBookBeans) {
        if (page == 0) {
            mSmartRefreshLayout.finishRefresh();
            bookListAdapter.setNewData(listBookBeans);
        } else {
            bookListAdapter.addData(listBookBeans);
        }
    }

    @Override
    public SmartRefreshLayout getSmartRefreshLayout() {
        return mSmartRefreshLayout;
    }

    @Override
    public void collectionSuccess() {
        collectionNum++;
        tvCollectionNum.setText("收藏（" + collectionNum + "）");
        isCollection = true;
        ivCollection.setImageResource(R.mipmap.ic_booklist_collectioned);
        if (PreferenceUtil.getInstance(getApplication()).isShowCollectionDialog()) {
            dialog.show();
            PreferenceUtil.getInstance(getApplication()).setShowCollectionDialog();
        }
    }

    @Override
    public void cancellCollection() {
        isCollection = false;
        collectionNum--;
        tvCollectionNum.setText("收藏（" + collectionNum + "）");
        ivCollection.setImageResource(R.mipmap.ic_booklist_collection);
    }

    @Override
    public void showPraiseSuccess() {
        bookListAdapter.updataPraiseState(pos, 1);
    }

    @Override
    public void showCancellPraise() {
        bookListAdapter.updataPraiseState(pos, 0);
    }

    @Override
    public void showInfo(String info) {
        ToastUtil.makeShortToast(info);
    }

    @Override
    public void joinBookList() {
        bookListAdapter.updataAddBookListState(pos);
        EventBus.getDefault().post(new LoadBookEvent());

    }

    /**
     * 同步本地书架
     *
     * @param booksBeanList
     */
    @Override
    public void showlocalAndRemoteData(List<BookListBean.ListBookBean.BooksBean> booksBeanList) {
        showAuthor(booksBeanList);

    }

    /**
     * 请求头视图
     *
     * @return
     */
    public View getHeaderView() {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.adapter_booklistheader, null);
        tvBookName = view.findViewById(R.id.tvBookName);
        tvPageView = view.findViewById(R.id.tvPageView);
        llLabelContent = view.findViewById(R.id.llLabelContent);
        tvLabel = view.findViewById(R.id.tvLabel);
        tvDes = view.findViewById(R.id.tvDes);
        tvNumAndCollection = view.findViewById(R.id.tvNumAndCollection);
        tvTime = view.findViewById(R.id.tvTime);
        return view;
    }

    /**
     * 弹框
     */
    private void initDialog() {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_collection, null);
        builder = new AlertDialog.Builder(this, R.style.DialogStyle);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        TextView tvKnow = view.findViewById(R.id.tvKnow);
        tvKnow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != dialog) {
                    dialog.dismiss();
                }
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

            if (!NetworkUtils.isNetworkConnected(BookListActivity.this)) {
                ToastUtil.makeShortToast("网络异常");
                shareAction.close();
                return;
            }
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    if (!WXUtils.isWeixinAvilible(BookListActivity.this)) {
                        ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                        return;
                    }
                    break;
                case QZONE:
                case QQ:
                    if (!WXUtils.isQQClientAvailable(BookListActivity.this)) {
                        ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                        return;
                    }
                    break;
            }
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            showInfo("分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showInfo("取消分享");
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

}
